package com.liwenfeng;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.time.YearMonth;
import java.time.format.DateTimeFormatter;
import java.util.Map;
import java.util.TreeMap;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class ExecutorCompletableFutureTest {
    //    static final int INDEX = 0;
    static final int TIME = 1;
/*
    static final int ORDER_ID = 2;
    static final int PRODUCT_ID = 3;
    static final int CATEGORY_ID = 4;
    static final int CATEGORY_CODE = 5;
    static final int BRAND = 6;
    static final int PRICE = 7;
    static final int USER_ID = 8;
    static final int USER_AGE = 9;
    static final int USER_SEX = 10;
    static final int USER_REGION = 11;
*/

    static final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss z");

    static Logger logger = LoggerFactory.getLogger("Test");

    public static void main(String[] args) throws IOException {
        //CompletableFuture类方式实现异步操作，不用自己创建线程池
        logger.info("开始统计");
        CompletableFuture.supplyAsync(()->monthlySalesReport()).thenAccept(r->{
            for (Map.Entry<YearMonth, Long> e : r.entrySet()) {
                logger.info(e.toString());
            }
        });
        logger.info("执行其他操作");
        System.in.read();
    }

    private static Map<YearMonth, Long> monthlySalesReport() {
        try (Stream<String> lines = Files.lines(Path.of("src/main/resources/data.txt"))) {
            Map<YearMonth, Long> collect = lines.skip(1)
                    .map(line -> line.split(","))
                    .collect(Collectors.groupingBy(array -> YearMonth.from(formatter.parse(array[TIME])), TreeMap::new, Collectors.counting()
                    ));
            return collect;
        } catch (IOException e) {
            logger.warn("文件没找到");
            throw new RuntimeException(e);
        }
    }
}
